package cn.wangqi.personal.wxpay.util.webconfig;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * Created by admin on 2017/8/12.
 */
public class WxPayCore {
    private static Logger logger = Logger.getLogger(WxPayCore.class);
    public static String buildCode(HttpServletRequest request){
        NativePay nativePay = new NativePay();
        logger.info("构建微信订单开始");
        try {
            String out_trade_no = request.getParameter("out_trade_no");
            String total_fee = request.getParameter("total_fee");
            String subject = request.getParameter("subject");

            String wxPayUrl = nativePay.GetPayUrl(out_trade_no, total_fee, subject);
            wxPayUrl = "<a href=\"" + wxPayUrl + "\"><img src=\"data:image/png;base64," + Base64.getEncoder().encodeToString(QRCode.from(wxPayUrl).to(ImageType.PNG).stream().toByteArray()) + "\" width=\"298\"/></a>";
            return wxPayUrl;
        } catch (NoSuchAlgorithmException e) {
            logger.error("执行buildWxPayUrl方法NoSuchAlgorithmException异常:" + e.getMessage(), e);
        } catch (ParserConfigurationException e) {
            logger.error("执行buildWxPayUrl方法ParserConfigurationException异常:" + e.getMessage(), e);
        } catch (SAXException e) {
            logger.error("执行buildWxPayUrl方法SAXException异常:" + e.getMessage(), e);
        } catch (IOException e) {
            logger.error("执行buildWxPayUrl方法IOException异常:" + e.getMessage(), e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
